package com.alfred.springboot.weblogaspect.handler;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: alfred
 * @date: 2021/7/20
 * @description: 接口日志 AOP 处理类
 */
@Slf4j
@Aspect
@Component
public class WebLogAspectHandler {

    @Pointcut("execution(* com.alfred.springboot.weblogaspect.controller..*.*(..))")
    public void webLog() {
        // 不做处理
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        String args = JSONUtil.toJsonStr(joinPoint.getArgs());
        log.info("==========> 前端请求, 请求路径:{}, 请求方法:{}, IP地址:{}, 类方法:{}, 参数:{}",
                request.getRequestURL(), request.getMethod(), request.getRemoteAddr(),
                joinPoint.getSignature().getDeclaringTypeName() + "." +
                        joinPoint.getSignature().getName(), args);
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        // 处理完请求，返回内容
        String returnStr = JSONUtil.toJsonStr(ret);
        log.info("==========> 响应内容返回 : {}", returnStr);
    }

}
